﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using Microsoft.Practices.ServiceLocation;
using NTweet.HttpService;

namespace NTweet {
	public class Client {
		IHttpRequestFactory requestFactory;

		/// <summary>
		/// Initializes a new instance of the <see cref="Client"/> class, using the ServiceLocator to get all the required services.
		/// </summary>
		public Client()
			: this(
				ServiceLocator.Current.GetInstance<IHttpRequestFactory>()
			) { }

		public Client(IHttpRequestFactory requestFactory) {
			this.requestFactory = requestFactory;
			if (requestFactory.DefaultCookieContainer == null)
				requestFactory.DefaultCookieContainer = new CookieContainer();
		}

		public ClientState State {
			get { return m_State; }
			private set {
				if (!Object.Equals(m_State, value)) {
					m_State = value;
					OnStateChanged(EventArgs.Empty);
				}
			}
		}
		private ClientState m_State;

		public event EventHandler StateChanged;
		protected virtual void OnStateChanged(EventArgs e) {
			if (StateChanged != null) StateChanged(this, e);
		}

		public bool Login(ICredentials credentials) {
			if (requestFactory.DefaultCredentials != null)
				Logout();
			var request = requestFactory.CreateRequest("http://twitter.com/account/verify_credentials.json");
			request.Credentials = credentials;
			var response = request.GetResponse();
			if (response.StatusCode == HttpStatusCode.OK) {
				requestFactory.DefaultCredentials = credentials;
				return true;
			} else {
				return false;
			}
		}

		public void Logout() {
			// TODO: Implement NTweet.Client.Logout
		}
	}
}
